package net.gldwork.srcpdr;

import java.util.LinkedList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

public class Method {
	private String name;
	private String accessModifier;
	private String returnType;
	private ContentBlock body = new ContentBlock();
	private List<String> params = new LinkedList<String>();
	private List<String> throwClass = new LinkedList<String>();
	private List<String> annotations = new LinkedList<String>();

	public Method(String name, String returnType, String accessModifier) {
		this.name = name;
		this.returnType = returnType;
		this.accessModifier = accessModifier;
	}

	public Method addBodyLine(String code, int indentCount) {
		body.addLine(code, indentCount);

		return this;
	}

	public ContentBlock toContentBlock() {
		ContentBlock cb = new ContentBlock();
		for (String anno : annotations) {
			cb.addLine(anno);
		}

		StringBuffer head = new StringBuffer();
		head.append(accessModifier).append(" ").append(returnType).append(" ")
				.append(name).append("(").append(StringUtils.join(params, ","))
				.append(") ");
		if (throwClass.size() > 0) {
			head.append("throws ").append(StringUtils.join(throwClass, ","));

		}
		head.append(" {");
		cb.addLine(head.toString());
		cb.append(body, 1);
		cb.addLine("}");
		return cb;
	}

	public Method addThrow(String type) {

		if (!throwClass.contains(type)) {
			throwClass.add(type);
		}

		return this;
	}

	public Method addAnnotation(String anno) {

		if (!annotations.contains(anno)) {
			annotations.add(anno);
		}

		return this;
	}

	public Method addParam(String type, String name) {
		String str = type + " " + name;
		if (!params.contains(str)) {
			params.add(str);
		}

		return this;
	}

	public Method addBodyLine(String code) {
		return addBodyLine(code, 0);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getAccessModifier() {
		return accessModifier;
	}

	public void setAccessModifier(String accessModifier) {
		this.accessModifier = accessModifier;
	}

	public String getReturnType() {
		return returnType;
	}

	public void setReturnType(String returnType) {
		this.returnType = returnType;
	}

	public List<String> getParams() {
		return params;
	}

	public void setParams(List<String> params) {
		this.params = params;
	}

}
